package cn.tile.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.tile.util.DatabaseUtil;

public class BaseDao {
	private Connection conn;
	public BaseDao(Connection conn){
		this.conn=conn;
	}
	
	/**
	 * 增删改操作
	 * @param sql
	 * @param param
	 * @return
	 * @throws SQLException
	 */
	public int executeUpdate(String sql,Object... param) throws SQLException{
		int result=-1;
		PreparedStatement pstmt=null;
		try {
			pstmt=conn.prepareStatement(sql);
			for (int i = 0; i < param.length; i++) {
				pstmt.setObject(i+1, param[i]);
			}
			result=pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} finally{
			DatabaseUtil.closeAll(null, pstmt, null);
		}
		return result;
	}
	/**
	 * 查询操作
	 * @param sql
	 * @param param
	 * @return
	 * @throws SQLException
	 */
	public ResultSet executeQuery(String sql,Object... param) throws SQLException{
		ResultSet rs=null;
		PreparedStatement pstmt=null;
		try {
			pstmt=conn.prepareStatement(sql);
			for (int i = 0; i < param.length; i++) {
				pstmt.setObject(i+1, param[i]);
			}
			rs=pstmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} finally{
			DatabaseUtil.closeAll(null, pstmt, null);
		}
		return rs;
	}
}
